const {User,validateUser} = require('../../model/user');
const Joi = require('joi');
const bcrypt = require('bcrypt');
module.exports = async (req,res,next) => {

    try{
        await validateUser(req.body);
    }catch (e) {
        return res.redirect(`/admin/user-edit?message=${ e.message }`);
        //JSON.stringify()将对象数据类型转换为字符串数据类型
        // return next(JSON.stringify({path: '/admin/user-edit',message: e.message}));
    }
    let user = await User.findOne({email: req.body.email});
    if (user) {
        return res.redirect(`/admin/user-edit?message=邮箱已被占用`);
        // return next(JSON.stringify({path: "/admin/user-edit",message: "邮箱已被占用"}));
    }
    const salt = await bcrypt.genSalt(10);
    const pass = await bcrypt.hash(req.body.password,salt);
    req.body.password = pass;
    console.log(req.body);
    await User.create(req.body);
    res.redirect('/admin/user');
};